const express = require('express')
const mysql = require('mysql')
const db = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456789',
  database: 'learner'
})
// title, description, href
module.exports = function () {
  let router = express.Router()

  router.get('/', (req, res) => {
    db.query(`SELECT * FROM introduce_table`, (err, intros) => {
      if (err) {
        console.error(err)
        res.status(500).send('database error').end()
      } else {
        res.render('admin/intro.ejs', { intros })
      }
    })
  })

  router.post('/', (req, res) => {
    let title = req.body.title
    let description = req.body.description
    let href = req.body.href
    db.query(`INSERT INTO introduce_table (title, description, href) VALUE ('${title}', '${description}', '${href}')`, (err, data) => {
      if (err) {
        console.error(err)
        res.status(500).send('database error').end()
      } else {
        res.redirect('/admin/intro')
      }
    })
  })

  return router
}
